package com.imu.purse.api.controller.trade;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.purse.api.controller.ApiAbstractController;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.trade.entity.YmbDetailEntity;
import com.imu.purse.modules.trade.entity.YmbWithdrawEntity;
import com.imu.purse.modules.trade.form.RechargeForm;
import com.imu.purse.modules.trade.form.YmbWithdrawForm;
import com.imu.purse.modules.trade.service.YmbDetailService;
import com.imu.purse.modules.trade.service.YmbWithdrawService;
import com.imu.security.SessionTokenProviderFactory;
import com.imu.utils.RSASignature;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 私募接口
 * @author sunhongwei
 * @email sunhongwei@gmail.com
 * @date 2018-03-22 17:27
 */
@RestController
@RequestMapping("/api/ymb")
@Api(tags="易买宝接口")
public class ApiYmbController extends ApiAbstractController
{
	@PostMapping("charge")
    @ApiOperation(value = "充值",notes = "充值说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SIGN", 	  value = "签名",  required = true),
            @ApiImplicitParam(paramType = "body",   dataType="RechargeForm", name = "form", 	  value = "充值",	  required = true)
    })
    public R rcharge(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, @RequestHeader("X-IMU-SIGN") String sign, @RequestBody RechargeForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form, AddGroup.class);
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        if (StrUtil.isBlank(uid)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
        
        //校验签名信息
        if (!RSASignature.verifySign(JSON.toJSONString(form), sign, this.pubKey)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SIGN_VERIFY_ERR);
        }

        //根据id获取该用户的手机号码
        ImuUserEntity user = userService.findById(Long.valueOf(uid));
        if(null == user || StrUtil.isBlank(user.getPhone())){
            return ErrorUtil.errorMesg(request,ErrorDesc.GET_USER_ERR);
        }
        
        //记录充值明细
        YmbDetailEntity entity = new YmbDetailEntity();
        entity.setUserId(Long.valueOf(uid));
        entity.setMoney(form.getMoney());
        entity.setPhone(user.getPhone());
        service.save(entity);
        return R.ok(1);
    }
    
    @GetMapping("rcharge")
    @ApiOperation(value = "查询充值",notes = "查询充值说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "page",  value = "页码",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "limit", value = "记录",  required = true)
    })
    public R rcharge(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, Integer page, Integer limit) {
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        
        if (StrUtil.isBlank(uid)) 
        {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
        
        YmbDetailEntity entity = new YmbDetailEntity();
        entity.setUserId(Long.valueOf(uid));
        entity.setPage(page);
        entity.setLimit(limit);
        return R.ok(1).put("data", service.queryList(entity));
    }
    
    @PostMapping("withdraw")
    @ApiOperation(value = "提现",notes = "提现说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SIGN", 	  value = "签名",  required = true),
            @ApiImplicitParam(paramType = "body",   dataType="YmbWithdrawForm", name = "form", 	  value = "提现",	  required = true)
    })
    public R withdraw(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, @RequestHeader("X-IMU-SIGN") String sign, @RequestBody YmbWithdrawForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form, AddGroup.class);
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        if (StrUtil.isBlank(uid)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
        
        //校验签名信息
        if (!RSASignature.verifySign(JSON.toJSONString(form), sign, this.pubKey)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SIGN_VERIFY_ERR);
        }
        
        //验证图片验证码是否正确
        String picPass = form.getAcode().toLowerCase();
        if(StrUtil.isBlank(redisTemplate.opsForValue().get(picPass))){
            return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
        }
        
        //验证支付密码
        ImuUserEntity user = userService.findById(Long.valueOf(uid));
        //校验支付密码正确性
        if(user == null || StrUtil.isBlank(user.getPayPwd()) || !user.getPayPwd().equals(new Sha256Hash(form.getPwd()).toHex()))
        {
            return ErrorUtil.errorMesg(request,ErrorDesc.TRADE_PWD_ERROR);
        }
        //验证银行卡信息
        if(StrUtil.isBlank(user.getBankNo()) || StrUtil.isBlank(user.getBankAccount()))
        {
            return ErrorUtil.errorMesg(request,ErrorDesc.BANK_ERROR);
        }
        
        //充值验证
        YmbWithdrawEntity entity = new YmbWithdrawEntity();
        BeanUtil.copyProperties(form, entity);
        entity.setUserId(Long.valueOf(uid));
        withdrawService.withdraw("withdraw:ymb", entity);
        
        //删除图片验证码
        redisTemplate.delete(picPass);
        return R.ok(1);
    }
    
    @GetMapping("withdraw")
    @ApiOperation(value = "查询提现",notes = "查询提现说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "page",  value = "页码",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "limit", value = "记录",  required = true)
    })
    public R withdraw(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, Integer page, Integer limit) {
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        
        if (StrUtil.isBlank(uid)) 
        {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }

        YmbWithdrawEntity entity = new YmbWithdrawEntity();
        entity.setUserId(Long.valueOf(uid));
        entity.setPage(page);
        entity.setLimit(limit);
        return R.ok(1).put("data", withdrawService.queryList(entity));
    }
	
    @Autowired
    private YmbDetailService service;

    @Autowired
    private YmbWithdrawService withdrawService;

	@Autowired
	private ImuUserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
	
    /****
     *公钥解密
     */
    @Value("${app.pay.pub-key}")
    private String pubKey;
}
